import {Collection, ListCollectionsResponse} from "../types/proto/api/v1/collection_service";
import {create} from "zustand";
import axios from "axios";

interface CollectionState {
  collectionMapById: Record<number, Collection>; // JM：表示一个对象的
  fetchCollectionList: (instanceUrl: string, accessToken: string) => Promise<Collection[]>;
  // getOrFetchCollectionById: (id: number) => Promise<Collection>;
  getCollectionById: (id: number) => Collection;
  getCollectionList: () => Collection[];
}

const useCollectionStore = create<CollectionState>()((set, get) => ({
  collectionMapById: {},
  fetchCollectionList: async (instanceUrl: string, accessToken: string) => {
    const normalizedUrl = instanceUrl.replace(/\/+$/, "");
    const {
      data: { collections },
    } = await axios.get<ListCollectionsResponse>(`${normalizedUrl}/api/v1/collections`, {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });
    const collectionMap = get().collectionMapById;
    collections.forEach((collection) => {
      collectionMap[collection.id] = collection;
    });
    set(collectionMap);
    return collections;
  },
  // getOrFetchCollectionById: async (id: number) => {
  //   const collectionMap = get().collectionMapById;
  //   if (collectionMap[id]) {
  //     return collectionMap[id] as Collection;
  //   }
  //
  //   const { collection } = await collectionServiceClient.getCollection({
  //     id: id,
  //   });
  //   if (!collection) {
  //     throw new Error(`Collection with id ${id} not found`);
  //   }
  //
  //   collectionMap[id] = collection;
  //   set(collectionMap);
  //   return collection;
  // },
  getCollectionById: (id: number) => {
    const collectionMap = get().collectionMapById;
    return collectionMap[id] as Collection;
  },
  getCollectionList: () => {
    return Object.values(get().collectionMapById);
  },
}));

export default useCollectionStore;
